function [I,labels,I_test,labels_test] = loadDataset(num, binary)
% Read dataset

% Training set
path = 'train-images.idx3-ubyte';
fid = fopen(path,'r','b');
magicNum = fread(fid,1,'int32');
if(magicNum~=2051) 
    display('Error: cant find magic number');
    return;
end
imgNum = fread(fid,1,'int32');
rowSz = fread(fid,1,'int32');
colSz = fread(fid,1,'int32');

if (num < imgNum)
    imgNum = num;
end

train_perm = randperm(imgNum);
for k=1:imgNum
    if (binary)
        temp = uint8(fread(fid,[rowSz colSz],'uchar'));
        meanThreshold = mean(temp(:));
        I{train_perm(k)} = temp >= meanThreshold;
    else
        I{train_perm(k)} = uint8(fread(fid,[rowSz colSz],'uchar'));
    end
end
fclose(fid);

% Training labels
path = 'train-labels.idx1-ubyte';
fid = fopen(path,'r','b');
magicNum = fread(fid,1,'int32');
if(magicNum~=2049) 
    display('Error: cant find magic number');
    return;
end
itmNum = fread(fid,1,'int32');

if (num < itmNum)
    itmNum = num;
end

readLabels = uint8(fread(fid,itmNum,'uint8'));
labels = zeros(itmNum, 1);
for permIndex = 1:length(train_perm)
    labels(train_perm(permIndex)) = readLabels(permIndex);
end

fclose(fid);

% Test images
path = 't10k-images.idx3-ubyte';
fid = fopen(path,'r','b');
magicNum = fread(fid,1,'int32');    
if(magicNum~=2051) 
    display('Error: cant find magic number');
    return;
end
imgNum = fread(fid,1,'int32');
rowSz = fread(fid,1,'int32');
colSz = fread(fid,1,'int32');

test_perm = randperm(imgNum);
for k=1:imgNum
    if (binary)
        temp = uint8(fread(fid,[rowSz colSz],'uchar'));
        meanThreshold = mean(temp(:));
        I_test{test_perm(k)} = temp >= meanThreshold;
    else
        I_test{test_perm(k)} = uint8(fread(fid,[rowSz colSz],'uchar'));
    end
end
fclose(fid);

% Test labels
path = 't10k-labels.idx1-ubyte';
fid = fopen(path,'r','b');
magicNum = fread(fid,1,'int32');
if(magicNum~=2049) 
    display('Error: cant find magic number');
    return;
end
itmNum = fread(fid,1,'int32');
readLabels_test = uint8(fread(fid,itmNum,'uint8'));
labels_test = zeros(itmNum, 1);
for permIndex = 1:length(test_perm)
    labels_test(test_perm(permIndex)) = readLabels_test(permIndex);
end

fclose(fid);